from typing import List

from django33.core.paginator import Paginator

from django33_ninja import NinjaAPI, Schema, Query

from myapp.models import User

# 创建 Django-Ninja API 实例
api = NinjaAPI()


# 定义用户 Schema
class UserSchema(Schema):
    name: str
    age: int


# 创建用户 Schema（用于返回用户数据）
class UserCreateSchema(Schema):
    id: int
    name: str
    age: int


# 分页响应 Schema
class PaginatedUserSchema(Schema):
    data: List[UserCreateSchema]  # 当前页的用户列表
    total: int  # 总用户数
    page: int  # 当前页码
    size: int  # 每页大小


# 获取所有用户（分页）
@api.get("/users", response=PaginatedUserSchema)
def list_users(request, page: int = Query(1, ge=1), size: int = Query(10, ge=1, le=100)):
    """
    获取所有用户（分页查询）
    - page: 当前页码（默认第 1 页）
    - size: 每页大小（默认 10 条，最大 100 条）
    """
    users = User.objects.all().order_by("id")  # 按 ID 排序
    paginator = Paginator(users, size)  # 创建分页器
    page_obj = paginator.page(page)  # 获取当前页数据

    return {
        "data": list(page_obj.object_list),  # 当前页的用户列表
        "total": paginator.count,  # 总用户数
        "page": page,  # 当前页码
        "size": size,  # 每页大小
    }


# 创建用户
@api.post("/users", response=UserCreateSchema)
def create_user(request, payload: UserSchema):
    user = User.objects.create(**payload.dict())
    return user


# 获取单个用户
@api.get("/users/{user_id}", response=UserCreateSchema)
def get_user(request, user_id: int):
    user = User.objects.get(id=user_id)
    return user


# 更新用户
@api.put("/users/{user_id}", response=UserCreateSchema)
def update_user(request, user_id: int, payload: UserSchema):
    user = User.objects.get(id=user_id)
    for attr, value in payload.dict().items():
        setattr(user, attr, value)
    user.save()
    return user


# 删除用户
@api.delete("/users/{user_id}")
def delete_user(request, user_id: int):
    user = User.objects.get(id=user_id)
    user.delete()
    return {"success": True}
